package com.ljkj.zjf.common;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ҵ�񵥺ŷ�����
 * ��ˮ�Ÿ�ʽΪyyyyMMddXXXX���涨ÿ��ֻ�ܵ�9999
 * @author liangf
 *
 */
public class BusinessNoGenerater {
	private static final String fileName = "businessid.txt";

	private static BusinessNoGenerater primaryGenerater = null;

	private BusinessNoGenerater() {
	}

	/**
	 * ȡ��PrimaryGenerater�ĵ���ʵ��
	 * 
	 * @return
	 */
	public static BusinessNoGenerater getInstance() {
		if (primaryGenerater == null) {
			synchronized (BusinessNoGenerater.class) {
				if (primaryGenerater == null) {
					primaryGenerater = new BusinessNoGenerater();
				}
			}
		}
		return primaryGenerater;
	}

	/**
	 * �����һ�����
	 */
	public synchronized String generaterNextNo(){
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		String today = formatter.format(date);
		
		//��ȡ�ļ��еı��
		String file_no = readfile();
		
		String new_no = ""; //�±��
		DecimalFormat df = new DecimalFormat("0000");
		if(file_no == null || file_no.equals("")){
			new_no = today + "0001";
		}else{
			String file_no_date = file_no.substring(0,8);
			String file_no_number = file_no.substring(8);
			if(today.equals(file_no_date)){
				new_no = file_no_date + df.format(1 + Integer.parseInt(file_no_number));
			}else{
				new_no = today + "0001";
			}
		}
		
		//д�ļ�
		writefile(new_no);
		return new_no;
		
	}
	
	/**
	 * /���ļ��еı��
	 */
	public synchronized String readfile(){
		InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String businessid = "";
        try{
        	businessid = br.readLine();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                	br.close();
                } catch (IOException e1) {
                }
            }
        }
        return businessid;
	}
	
	/**
	 * �����±��д���ļ���
	 * @param businessid
	 */
	public synchronized void writefile(String businessid){
		try {
            //��һ��д�ļ��������캯���еĵڶ�������false��ʾ�Ը�����ʽд�ļ�
        	String filepath = Thread.currentThread().getContextClassLoader().getResource(fileName).getPath();
            FileWriter writer = new FileWriter(filepath, false);
            writer.write(businessid);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}